package com.itheima.controller;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import com.itheima.common.vo.ResultVo;
import com.itheima.dfs.model.BaseFileModel;
import com.itheima.dfs.template.DfsTemplate;
import com.itheima.wemedia.feign.WmMaterialFeign;
import com.itheima.wemedia.pojo.WmMaterial;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Cheneg
 * @version 1.0
 */

@RestController
@RequestMapping("/dfs")
@Slf4j
@Api(tags = "分布式文件管理")
public class FileController {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private DfsTemplate dfsTemplate;

    @Autowired
    private WmMaterialFeign wmMaterialFeign;

    /*    @Autowired
        private FdfsWebServer webServer;*/


    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public ResultVo uploadFile(MultipartFile multipartFile) {

        // 获取请求的来源
        String from = RequestContextUtil.getHeader(SystemConstants.USER_HEADER_FROM);
        if (StringUtils.isEmpty(from)) {
            throw new LeadNewsException("文件上传失败!");
        }

        // 获取源文件名

        String filename = multipartFile.getOriginalFilename();
        String ext = StringUtils.getFilenameExtension(filename);
        try {
            /*          不用模板的
            //上传文件
            //     * @param inputStream
            //     * @param fileSize
            //     * @param fileExtName
            //     * @param metaDataSet
           StorePath storePath = client.uploadFile(
                    multipartFile.getInputStream(),
                    multipartFile.getSize(),
                    ext,
                    null);
            // 文件ID
            String fileId = storePath.getFullPath();*/
            //使用模板的
            String fileId = dfsTemplate.uploadFile(new BaseFileModel("itheima", multipartFile.getSize(), filename, multipartFile.getBytes()));
            // 远程调用自媒体微服，添加素材信息
            if (SystemConstants.WEMEDIA_PIC.equals(from)) {
                addWmMaterial(fileId);
            }
            ////拼接路径
            //String url = webServer.getWebServerUrl() + storePath.getFullPath();

            //返回文件路径
            return ResultVo.ok(Collections.singletonMap("url", fdfsWebServer.getWebServerUrl() + fileId));
        } catch (IOException e) {
            log.error("文件上传失败", e);
        }
        return ResultVo.bizError("上传文件失败");
    }


    /**
     * 远程调用自媒体 添加素材
     *
     * @param fileId
     */
    private void addWmMaterial(String fileId) {
        WmMaterial material = new WmMaterial();
        material.setUrl(fileId);
        material.setIsCollection(0);//0：不是收藏
        material.setCreatedTime(LocalDateTime.now());
        material.setType(0);// 0：图片
        //material.setUserId(Integer.parseInt(RequestContextUtil.getUserId()));
        material.setUserId(Long.valueOf(RequestContextUtil.getUserId()));
        //2. 远程调用
        ResultVo result = wmMaterialFeign.add(material);
        //3. 调用失败要报错
        if (!result.isSuccess()) {
            throw new LeadNewsException("文件上传，调用自媒体添加素材失败");
        }
    }


    /**
     * 批量下载文件
     * @param fileIds
     * @return
     */
    @PostMapping("/download")
    public ResultVo<List<byte[]>> download(@RequestBody List<String> fileIds){
        // 有内容才下载
        if(!CollectionUtils.isEmpty(fileIds)){
            // 下载文件的字节数组处理器
            DownloadByteArray dba = new DownloadByteArray();
            List<byte[]> list = fileIds.stream().map(fileId -> {
                // 解析图片地址
                StorePath storePath = StorePath.parseFromUrl(fileId);
                // 下载文件为字节数组
                byte[] bytes = client.downloadFile(storePath.getGroup(), storePath.getPath(), dba);
                return bytes;
            }).collect(Collectors.toList());
            return ResultVo.ok(list);
        }
        return ResultVo.ok();
    }
}

